# API Docs: https://reqable.com/docs/capture/addons

from reqable import *
import mysql.connector
import json
import requests
import base64

def onRequest(context, request):
  # Print url to console
  print('request url ' + context.url)
  print('aaaaaaaaaaa ' + request.headers)
  # tempJson = request.headers.toJson()
  # log_json_array = request.headers.toJson()
  
  # print('log_json_array：'+ log_json_array['authorization'])
  if request.headers['authorization'] is not None:
    print(request.headers['authorization'])
    
    if request.headers['authorization'] is not None:
      json_data = {
          'refresh': request.headers['authorization'].replace("Bearer ",""),
      }
      
      global_headers = {
        'Host': 'gateway.blum.codes',
        'sec-ch-ua': '"Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99", "Microsoft Edge WebView2";v="124"',
        'accept': 'application/json, text/plain, */*',
        'content-type': 'application/json',
        'sec-ch-ua-mobile': '?0',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
        'sec-ch-ua-platform': '"Windows"',
        'origin': 'https://telegram.blum.codes',
        'sec-fetch-site': 'same-site',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'priority': 'u=1, i',
      }
      print("刷新111")
      response = requests.post('https://gateway.blum.codes/v1/auth/refresh', headers=global_headers, json=json_data, verify=False)
      print("刷新结果")
      print(response.content)
      refrest_response_json = json.loads(response.content)

      if "access" in refrest_response_json:
        # 刷新token成功
        access_token = refrest_response_json['access']
        refreshedAccessToken = "Bearer " + refrest_response_json['access']
        
        refresh_token = refrest_response_json['refresh']
        refreshedRefreshToken = "Bearer " + refrest_response_json['refresh']
        
        print("刷新到的 REFRESH TOKEN：", refreshedAccessToken )
        
        # 把新的token写入数据库
        # cnx = mysql.connector.connect(user='root', password='admin1234',
                                    # host='localhost', database='blumtokens')
        # 使用cursor()方法获取操作游标 
        # cursor = cnx.cursor()

        # 解析刚获取到的access token, 用.号进行split
        access_token_splited = access_token.split(".")
        access_token_splited_token_index1 = access_token_splited[1]
        
        # 解析刚获取到的refresh token, 用.号进行split
        refresh_token_splited = refresh_token.split(".")
        refresh_token_splited_token_index1 = refresh_token_splited[1]

        # base64解析 access token
        access_token_splited_token_index1 += "=" * ((4 - len(access_token_splited_token_index1) % 4) % 4)
        access_token_decoded_string = base64.b64decode(access_token_splited_token_index1)
        access_token_decoded_string_utf8 = access_token_decoded_string.decode("utf-8")

        # print("ttttt")
        access_token_parsed_token_json = json.loads(access_token_decoded_string_utf8)

        access_token_token_expire_timestamp = access_token_parsed_token_json['exp']
        game_id = access_token_parsed_token_json['sub']
        
        # base64解析 refresh token
        refresh_token_splited_token_index1 += "=" * ((4 - len(refresh_token_splited_token_index1) % 4) % 4)
        refresh_token_decoded_string = base64.b64decode(refresh_token_splited_token_index1)
        refresh_token_decoded_string_utf8 = refresh_token_decoded_string.decode("utf-8")

        # print("ttttt")
        refresh_token_parsed_token_json = json.loads(refresh_token_decoded_string_utf8)

        refresh_token_token_expire_timestamp = refresh_token_parsed_token_json['exp']
        # game_id = parsed_token_json['sub']
        # payload = json.dumps({
        #         "game_id":""+game_id,
        #         "access_token":refreshedAccessToken,
        #         "access_token_expire":access_token_token_expire_timestamp,
        #         "refresh_token":refreshedRefreshToken,
        #         "refresh_token_expire":refresh_token_token_expire_timestamp
        # })
        
        payload = {
                "game_id":""+game_id,
                "access_token":refreshedAccessToken,
                "access_token_expire":access_token_token_expire_timestamp,
                "refresh_token":refreshedRefreshToken,
                "refresh_token_expire":refresh_token_token_expire_timestamp
        }
        
        headers_a = {
          'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",
          'Accept': "application/json, text/plain, */*",
          'Accept-Encoding': "gzip, deflate, br, zstd",
          'Content-Type': "application/json",
          'sec-ch-ua': "\"Chromium\";v=\"124\", \"Microsoft Edge\";v=\"124\", \"Not-A.Brand\";v=\"99\", \"Microsoft Edge WebView2\";v=\"124\"",
          'sec-ch-ua-mobile': "?0",
          'sec-ch-ua-platform': "\"Windows\"",
          'sec-fetch-site': "same-site",
          'sec-fetch-mode': "cors",
          'sec-fetch-dest': "empty",
          'accept-language': "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
          'priority': "u=1, i"
        }
        
        update_result_response = requests.post('http://airdrop.kimoji.top/api/blum/token', headers=headers_a, json=payload, verify=False, timeout=8)
        print(payload)
        print(update_result_response.content)
    
        # SQL 插入语句
        # query = "INSERT INTO blumtoken_temp(token) VALUES ('{}')".format(self.refreshedAccessToken)
        # query = "INSERT INTO blumtoken (game_id, access_token, access_token_expire, refresh_token, refresh_token_expire) VALUES ('{}', '{}', '{}', '{}', '{}') ON DUPLICATE KEY UPDATE access_token = '{}', access_token_expire = '{}' ,refresh_token = '{}', refresh_token_expire = '{}'".format(game_id, refreshedAccessToken, access_token_token_expire_timestamp, refreshedRefreshToken, refresh_token_token_expire_timestamp,  refreshedAccessToken, access_token_token_expire_timestamp, refreshedRefreshToken, refresh_token_token_expire_timestamp)
        # INSERT INTO users (id, name) VALUES (1, 'Alice') ON DUPLICATE KEY UPDATE name = 'Alice';
        # values = ('aa')
        # cursor.execute(query)
    
        # cnx.commit()
        # cursor.close()
        # cnx.close()
        
        print("写入数据库成功！")
      else:
        print("ppppp")

      # # print(response.content)

      # refreshedAccessToken = "Bearer " + refrest_response_json['access']
      
      # cnx = mysql.connector.connect(user='root', password='admin1234',
      #                             host='localhost', database='blumtokens')
      # # 使用cursor()方法获取操作游标 
      # cursor = cnx.cursor()
    
      # # SQL 插入语句
      # query = "INSERT INTO blumtoken(token) VALUES ('{}')".format(refreshedAccessToken)
      # # values = ('aa')
      # cursor.execute(query)
    
      # cnx.commit()
      # cursor.close()
      # cnx.close()
  #   print('-------------------------------------------------------------')
  #   print(log_json_array['authorization'])
  #   print('=============================================================')
    # print('authorization: '+ log_json_array['authorization'])
  # else:
  #   print('authorization: '+log_json_array.get('authorization'))
    
  # Update or add a query parameter
  # request.queries['foo'] = 'bar'

  # Update or add a http header
  # request.headers['foo'] = 'bar'

  # Replace http body with a text
  # request.body = 'Hello World'

  # Map with a local file
  # request.body.file('~/Desktop/body.json')

  # Convert to dict if the body is a JSON
  # request.body.jsonify()
  # Update the JSON content
  # request.body['foo'] = 'bar'

  # Done
  

  
  return request

def onResponse(context, response):
  # Update status code
  # response.code = 404

  # APIs are same as `onRequest`

  # Done
  return response

